<template>
  <el-dialog
    v-model="dialogVisible"
    title="编辑用户"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px" label-position="right">
      <!-- 基本信息 -->
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名" clearable maxlength="50" show-word-limit />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="formData.password"
          type="password"
          placeholder="留空则不修改密码"
          clearable
          maxlength="100"
          show-password
        />
        <div class="form-tip">
          <el-text size="small" type="info">留空则不修改当前密码</el-text>
        </div>
      </el-form-item>

      <!-- 个人资料 -->
      <el-divider content-position="left">个人资料</el-divider>

      <el-form-item label="邮箱" prop="profile.email">
        <el-input v-model="formData.profile.email" placeholder="请输入邮箱地址" clearable maxlength="100" />
      </el-form-item>

      <el-form-item label="性别" prop="profile.gender">
        <el-radio-group v-model="formData.profile.gender">
          <el-radio :label="Gender.FEMALE">女</el-radio>
          <el-radio :label="Gender.MALE">男</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="地址" prop="profile.address">
        <el-input
          v-model="formData.profile.address"
          type="textarea"
          placeholder="请输入地址"
          :rows="3"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="头像" prop="profile.photo">
        <div class="avatar-section">
          <div class="avatar-input-group">
            <el-input
              v-model="formData.profile.photo"
              placeholder="请输入头像URL（可选）"
              clearable
              maxlength="500"
              class="avatar-input"
            />
            <el-button
              type="primary"
              plain
              @click="generateRandomAvatar"
              :loading="avatarGenerating"
              class="generate-btn"
            >
              {{ avatarGenerating ? "生成中..." : "随机生成" }}
            </el-button>
          </div>
          <div v-if="formData.profile.photo" class="avatar-preview">
            <div class="preview-container">
              <el-avatar :size="80" :src="formData.profile.photo" fit="cover" class="preview-avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <div class="preview-info">
                <el-text size="small" type="info">头像预览</el-text>
                <el-text size="small" type="info" class="preview-tip">点击随机生成可更换头像</el-text>
              </div>
            </div>
          </div>
        </div>
      </el-form-item>

      <!-- 角色分配 -->
      <el-divider content-position="left">角色分配</el-divider>

      <el-form-item label="用户角色" prop="roles">
        <el-select
          v-model="formData.roles"
          multiple
          placeholder="请选择用户角色（可选）"
          style="width: 100%"
          :loading="roleLoading"
          clearable
          collapse-tags
          collapse-tags-tooltip
        >
          <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id" />
        </el-select>
        <div class="form-tip">
          <el-text size="small" type="info">可以为用户分配多个角色，也可以清空所有角色</el-text>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" :disabled="loading">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ loading ? "更新中..." : "确定" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { User } from "@element-plus/icons-vue";
import { useUserStore } from "@/stores/user";
import { roleApi } from "@/apis/role";
import type { User as UserType, CreateUserRequest, UpdateUserRequest } from "@/types/user";
import type { Role } from "@/types/role";
import { Gender } from "@/types/gender";

defineOptions({
  name: "EditUserDialog",
});

// Props & Emits
interface Props {
  modelValue: boolean;
  user?: UserType | null;
}

interface Emits {
  (e: "update:modelValue", value: boolean): void;
  (e: "success"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// Store
const userStore = useUserStore();

// 响应式数据
const formRef = ref<FormInstance>();
const loading = ref(false);
const roleList = ref<Role[]>([]);
const roleLoading = ref(false);
const avatarGenerating = ref(false);

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});

// 表单数据 - 确保 profile 始终存在
const formData = ref<CreateUserRequest & { profile: NonNullable<CreateUserRequest["profile"]> }>({
  username: "",
  password: "",
  profile: {
    email: "",
    gender: Gender.FEMALE,
    address: "",
    photo: "",
  },
  roles: [],
});

// 表单验证规则
const formRules: FormRules = {
  "username": [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 50, message: "用户名长度在 2 到 50 个字符", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5\s]+$/,
      message: "用户名只能包含字母、数字、下划线、中文和空格",
      trigger: "blur",
    },
  ],
  "password": [{ min: 6, max: 100, message: "密码长度在 6 到 100 个字符", trigger: "blur" }],
  "profile.email": [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
  ],
  "profile.gender": [{ required: true, message: "请选择性别", trigger: "change" }],
};

// 获取角色列表
const fetchRoles = async () => {
  try {
    roleLoading.value = true;
    const response = await roleApi.getRoles();
    // 根据后端返回的数据结构调整
    roleList.value = response.data || [];
  } catch (error) {
    console.error("获取角色列表失败:", error);
    ElMessage.error("获取角色列表失败");
    roleList.value = [];
  } finally {
    roleLoading.value = false;
  }
};

// 生成随机头像
const generateRandomAvatar = async () => {
  try {
    avatarGenerating.value = true;

    // 头像风格数组
    const avatarStyles = ["avataaars", "personas", "bottts", "identicon", "initials"];
    const randomStyle = avatarStyles[Math.floor(Math.random() * avatarStyles.length)];

    // 生成随机种子（基于当前时间戳和随机数）
    const seed = `${Date.now()}-${Math.random().toString(36).substring(2)}`;

    // 构建 DiceBear API URL
    const avatarUrl = `https://api.dicebear.com/7.x/${randomStyle}/svg?seed=${seed}&size=200`;

    // 设置生成的头像URL
    formData.value.profile.photo = avatarUrl;

    ElMessage.success("头像生成成功！");
  } catch (error) {
    console.error("生成头像失败:", error);
    ElMessage.error("生成头像失败，请重试");
  } finally {
    avatarGenerating.value = false;
  }
};

// 初始化表单数据
const initFormData = (user: UserType) => {
  console.log("初始化用户数据:", user);
  console.log("用户性别:", user.profile?.gender, "类型:", typeof user.profile?.gender);

  // 确保性别值正确转换
  let genderValue = Gender.FEMALE; // 默认值
  if (user.profile?.gender !== undefined) {
    // 处理可能的字符串或数字类型
    const rawGender = user.profile.gender;
    if (typeof rawGender === "string") {
      genderValue = parseInt(rawGender) as Gender;
    } else if (typeof rawGender === "number") {
      genderValue = rawGender as Gender;
    }
  }

  formData.value = {
    username: user.username || "",
    password: "", // 编辑时密码留空
    profile: {
      email: user.profile?.email || "",
      gender: genderValue,
      address: user.profile?.address || "",
      photo: user.profile?.photo || "",
    },
    roles: user.roles?.map((role: any) => role.id) || [],
  };

  console.log("表单数据性别:", formData.value.profile.gender, "类型:", typeof formData.value.profile.gender);
  console.log("Gender.FEMALE:", Gender.FEMALE, "Gender.MALE:", Gender.MALE);

  // 确保表单验证状态清除
  nextTick(() => {
    formRef.value?.clearValidate();
  });
};

// 重置表单
const resetForm = () => {
  formData.value = {
    username: "",
    password: "",
    profile: {
      email: "",
      gender: Gender.FEMALE,
      address: "",
      photo: "",
    },
    roles: [],
  };
  nextTick(() => {
    formRef.value?.clearValidate();
  });
};

// 关闭对话框
const handleClose = () => {
  if (loading.value) return;
  dialogVisible.value = false;
  resetForm();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value || !props.user) return;

  try {
    // 表单验证
    const valid = await formRef.value.validate();
    if (!valid) return;

    loading.value = true;

    // 准备提交数据，过滤空值
    const submitData: UpdateUserRequest = {
      username: formData.value.username,
      password: formData.value.password || undefined, // 空密码不提交
      profile: {
        email: formData.value.profile.email,
        gender: formData.value.profile.gender,
        address: formData.value.profile.address || undefined,
        photo: formData.value.profile.photo || undefined,
      },
      roles: formData.value.roles && formData.value.roles.length > 0 ? formData.value.roles : undefined,
    };

    // 调用 store 更新用户
    await userStore.updateUser(props.user.id, submitData);

    ElMessage.success("用户更新成功");
    emit("success");
    handleClose();
  } catch (error) {
    console.error("更新用户失败:", error);
    ElMessage.error("更新用户失败，请重试");
  } finally {
    loading.value = false;
  }
};

// 监听对话框打开，初始化表单数据并获取角色列表
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal && props.user) {
      nextTick(() => {
        initFormData(props.user!);
        fetchRoles();
      });
    }
  },
);

// 组件挂载时获取角色列表
onMounted(() => {
  fetchRoles();
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-divider__text) {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.form-tip {
  margin-top: 4px;
}

.avatar-section {
  width: 100%;
}

.avatar-input-group {
  display: flex;
  gap: 12px;
  align-items: stretch;
  margin-bottom: 16px;

  .avatar-input {
    flex: 1;
  }

  .generate-btn {
    min-width: 100px;
    height: auto;
    padding: 8px 16px;
    font-size: 14px;
    white-space: nowrap;
  }
}

.avatar-preview {
  margin-top: 12px;

  .preview-container {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 16px;
    background: linear-gradient(135deg, #f5f7fa 0%, #f0f2f5 100%);
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }

  .preview-avatar {
    border: 2px solid #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  .preview-info {
    display: flex;
    flex-direction: column;
    gap: 4px;

    .preview-tip {
      opacity: 0.7;
      font-size: 12px;
    }
  }
}
</style>
